package service

import (
	"goadmin/logs"
	"goadmin/models"
	"goadmin/utils"
	"gorm.io/gorm"
)

type OrderService struct{ db *gorm.DB }

func OrderList(pageInfo utils.PageInfo, query models.OrderQuery) (*utils.PageResult, error) {
	var orders []models.Order
	var total int64
	// 构建查询
	db := models.DB.Model(&models.Order{})
	// 添加查询条件
	if query.Mobile != "" {
		keyword := "%" + query.Mobile + "%"
		db = db.Where("mobile LIKE ?", keyword)
		logs.Sugar().Info("code失败错误信息--query.Mobile", query.Mobile)
	}
	// 获取总数
	if err := db.Count(&total).Error; err != nil {
		return nil, err
	}
	// 分页查询
	offset := pageInfo.GetOffset()
	pageSize := pageInfo.GetPageSize()
	if err := db.Preload("User").Offset(offset).Limit(pageSize).Order("created_at DESC").Find(&orders).Error; err != nil {
		return nil, err
	}
	// 返回分页结果
	return utils.NewPageResult(orders, total, pageInfo.GetPage(), pageSize), nil
}

// Get 根据 ID 获取商品详情
func OrderGet(id uint64) (p models.Order, err error) {
	err = models.DB.Model(&models.Order{}).Preload("User").Preload("OrderItems").First(&p, id).Error
	return p, err
}
func AddOrder(id uint64, quantity uint64, user_id int) (orderId uint64, err error) {
	p := models.Product{}
	err = models.DB.Model(&models.Product{}).First(&p, id).Error
	if err != nil {
		return 0, err
	}
	TotalAmount := p.Price * float64(quantity)
	// 1. 构造订单结构体
	order := models.Order{
		OrderNo:       utils.RandomStringWithTime(28),
		UserID:        user_id,
		TotalAmount:   p.Price * float64(quantity),
		Status:        0,
		TransactionID: "",
		PayStatus:     0,
		OutRefundNo:   "",
		RefundStatus:  0,
	}
	if err := models.DB.Create(&order).Error; err != nil {
		return 0, err
	}
	oi := models.OrderItem{
		OrderID:    order.ID,
		ProductID:  id,
		Quantity:   quantity,
		Price:      p.Price,
		TotalPrice: TotalAmount,
	}
	if err := models.DB.Create(&oi).Error; err != nil {
		return 0, err
	}
	return oi.ID, nil
}
